package com.ryan.demo.jackson.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.ryan.demo.jackson.model.AccountBean;

public class JsonParser {
	private JsonGenerator jsonGenerator = null;
	private ObjectMapper objectMapper = null;
	private AccountBean bean = null;

	@Before
	public void init() {
		bean = new AccountBean();
		bean.setAddress("china-Guangzhou");
		bean.setEmail("hoojo_@126.com");
		bean.setId(1);
		bean.setName("hoojo");
		objectMapper = new ObjectMapper();
		try {
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
					System.out, JsonEncoding.UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@After
	public void destory() {
		try {
			if (jsonGenerator != null) {
				jsonGenerator.flush();
			}
			if (!jsonGenerator.isClosed()) {
				jsonGenerator.close();
			}
			jsonGenerator = null;
			objectMapper = null;
			bean = null;
			System.gc();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * <b>function:</b>将java对象转换成json字符串
	 * @author hoojo
	 * @createDate 2010-11-23 下午06:01:10
	 */
	public void writeEntityJSON() {
	    
	    try {
	        System.out.println("jsonGenerator");
	        //writeObject可以转换java对象，eg:JavaBean/Map/List/Array等
	        jsonGenerator.writeObject(bean);    
	        System.out.println();
	        
	        System.out.println("ObjectMapper");
	        //writeValue具有和writeObject相同的功能
	        objectMapper.writeValue(System.out, bean);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	/**
	 * <b>function:</b>将map转换成json字符串
	 * @author hoojo
	 * @createDate 2010-11-23 下午06:05:26
	 */
	@Test
	public void writeMapJSON() {
	    try {
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("name", bean.getName());
	        map.put("account", bean);
	        bean = new AccountBean();
	        bean.setAddress("china-Beijin");
	        bean.setEmail("hoojo@qq.com");
	        map.put("account2", bean);
	        
	        System.out.println("jsonGenerator");
	        jsonGenerator.writeObject(map);
	        System.out.println("");
	        
	        System.out.println("objectMapper");
	        objectMapper.writeValue(System.out, map);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	public static void main(String [] args){
		JsonParser jsonParser = new JsonParser();
        
		jsonParser.init();
		
	    List<String> settleMerchantIdlist = null;
	    
	    List<String> acceptCardOrgList = null;
		
	    List<Map<String,String>> merchantExchangeRateList = null;
		
	    List<Map<String,String>> clearingCenterList = null;
		
	    List<Map<String,String>> bankMapList = null;
        
        settleMerchantIdlist = new ArrayList<String>();
        settleMerchantIdlist.add("1");
        settleMerchantIdlist.add("1");
        settleMerchantIdlist.add("3");
        settleMerchantIdlist.add("4");
		jsonParser.listToJson(settleMerchantIdlist);
        
        acceptCardOrgList = new ArrayList<String>();
        acceptCardOrgList.add("VI");
        acceptCardOrgList.add("MC");
        acceptCardOrgList.add("AX");
        acceptCardOrgList.add("CU");
		jsonParser.listToJson(acceptCardOrgList);
        
        merchantExchangeRateList = new ArrayList<Map<String,String>>();
        Map<String,String> merchantExchangeRate = new HashMap<String,String>();
        merchantExchangeRate.put("pricingCurrency","GBP");
        merchantExchangeRate.put("billingCurrency","GBP");
        merchantExchangeRate.put("exchangeDir","0");
        merchantExchangeRate.put("exchangeRate","1");
        merchantExchangeRateList.add(merchantExchangeRate);
        Map<String,String> merchantExchangeRate1 = new HashMap<String,String>();
        merchantExchangeRate1.put("pricingCurrency","JPY");
        merchantExchangeRate1.put("billingCurrency","GBP");
        merchantExchangeRate1.put("exchangeDir","1");
        merchantExchangeRate1.put("exchangeRate","34");
        merchantExchangeRateList.add(merchantExchangeRate1);
        Map<String,String> merchantExchangeRate2 = new HashMap<String,String>();
        merchantExchangeRate2.put("pricingCurrency","JPY");
        merchantExchangeRate2.put("billingCurrency","JPY");
        merchantExchangeRate2.put("exchangeDir","0");
        merchantExchangeRate2.put("exchangeRate","12");
        merchantExchangeRateList.add(merchantExchangeRate2);
		jsonParser.listToJson(merchantExchangeRateList);
        
        clearingCenterList = new ArrayList<Map<String,String>>();
        Map<String,String> clearingCenter = new HashMap<String,String>();
        clearingCenter.put("cardOrgCode","A");
        clearingCenter.put("clearingHouseCode","aaaa");
        clearingCenterList.add(clearingCenter);
        Map<String,String> clearingCenter1 = new HashMap<String,String>();
        clearingCenter1.put("cardOrgCode","A1");
        clearingCenter1.put("clearingHouseCode","aaaa1");
        clearingCenterList.add(clearingCenter1);
        Map<String,String> clearingCenter2 = new HashMap<String,String>();
        clearingCenter2.put("cardOrgCode","A2");
        clearingCenter2.put("clearingHouseCode","aaaa2");
        clearingCenterList.add(clearingCenter2);
        Map<String,String> clearingCenter3 = new HashMap<String,String>();
        clearingCenter3.put("cardOrgCode","A3");
        clearingCenter3.put("clearingHouseCode","aaaa3");
        clearingCenterList.add(clearingCenter3);
        Map<String,String> clearingCenter4 = new HashMap<String,String>();
        clearingCenter4.put("cardOrgCode","A4");
        clearingCenter4.put("clearingHouseCode","aaaa4");
        clearingCenterList.add(clearingCenter4);
		jsonParser.listToJson(clearingCenterList);
        
        bankMapList = new ArrayList<Map<String,String>>();
        Map<String,String> bankMap = new HashMap<String,String>();
        bankMap.put("bankCode","ccb");
        bankMap.put("rate","100");
        bankMapList.add(bankMap);
        Map<String,String> bankMap1 = new HashMap<String,String>();
        bankMap1.put("bankCode","abc");
        bankMap1.put("rate","113");
        bankMapList.add(bankMap1);
        Map<String,String> bankMap2 = new HashMap<String,String>();
        bankMap2.put("bankCode","cmbc");
        bankMap2.put("rate","111");
        bankMapList.add(bankMap2);
        Map<String,String> bankMap3 = new HashMap<String,String>();
        bankMap3.put("bankCode","icbc");
        bankMap3.put("rate","112");
        bankMapList.add(bankMap3);
		jsonParser.listToJson(bankMapList);
	}
	
	@SuppressWarnings("rawtypes")
	public void listToJson(List list) {
        System.out.println("jsonGenerator");
        try {
	        ObjectMapper objectMapper = new ObjectMapper();
	        OutputStream outputStream = new ByteArrayOutputStream();
	        JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8);
	        //list转换成JSON字符串
			jsonGenerator.writeObject(list);
			System.out.println(outputStream.toString());
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        System.out.println();
	}
	
	/**
	 * <b>function:</b>将list集合转换成json字符串
	 * @author hoojo
	 * @createDate 2010-11-23 下午06:05:59
	 */
	@Test
	public void writeListJSON() {
	    try {
	        List<AccountBean> list = new ArrayList<AccountBean>();
	        list.add(bean);
	        
	        bean = new AccountBean();
	        bean.setId(2);
	        bean.setAddress("address2");
	        bean.setEmail("email2");
	        bean.setName("haha2");
	        list.add(bean);
	        
	        System.out.println("jsonGenerator");
	        //list转换成JSON字符串
	        jsonGenerator.writeObject(list);
	        System.out.println();
	        System.out.println("ObjectMapper");
	        //用objectMapper直接返回list转换成的JSON字符串
	        System.out.println("1###" + objectMapper.writeValueAsString(list));
	        System.out.print("2###");
	        //objectMapper list转换成JSON字符串
	        objectMapper.writeValue(System.out, list);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	@Test
	public void writeOthersJSON() {
	    try {
	        String[] arr = { "a", "b", "c" };
	        System.out.println("jsonGenerator");
	        String str = "hello world jackson!";
	        //byte
	        jsonGenerator.writeBinary(str.getBytes());
	        //boolean
	        jsonGenerator.writeBoolean(true);
	        //null
	        jsonGenerator.writeNull();
	        //float
	        jsonGenerator.writeNumber(2.2f);
	        //char
	        jsonGenerator.writeRaw("c");
	        //String
	        jsonGenerator.writeRaw(str, 5, 10);
	        //String
	        jsonGenerator.writeRawValue(str, 5, 5);
	        //String
	        jsonGenerator.writeString(str);
	        jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
	        System.out.println();
	        
	        //Object
	        jsonGenerator.writeStartObject();//{
	        jsonGenerator.writeObjectFieldStart("user");//user:{
	        jsonGenerator.writeStringField("name", "jackson");//name:jackson
	        jsonGenerator.writeBooleanField("sex", true);//sex:true
	        jsonGenerator.writeNumberField("age", 22);//age:22
	        jsonGenerator.writeEndObject();//}
	        
	        jsonGenerator.writeArrayFieldStart("infos");//infos:[
	        jsonGenerator.writeNumber(22);//22
	        jsonGenerator.writeString("this is array");//this is array
	        jsonGenerator.writeEndArray();//]
	        
	        jsonGenerator.writeEndObject();//}
	        
	        
	        AccountBean bean = new AccountBean();
	        bean.setAddress("address");
	        bean.setEmail("email");
	        bean.setId(1);
	        bean.setName("haha");
	        //complex Object
	        jsonGenerator.writeStartObject();//{
	        jsonGenerator.writeObjectField("user", bean);//user:{bean}
	        jsonGenerator.writeObjectField("infos", arr);//infos:[array]
	        jsonGenerator.writeEndObject();//}
	        
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}

	@Test
	public void readJson2Entity() {
	    String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
	    try {
	        AccountBean acc = objectMapper.readValue(json, AccountBean.class);
	        System.out.println(acc.getName());
	        System.out.println(acc);
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	/**
	 * <b>function:</b>json字符串转换成list<map>
	 * @author hoojo
	 * @createDate 2010-11-23 下午06:12:01
	 */
	@SuppressWarnings("unchecked")
	@Test
	public void readJson2List() {
	    String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
	                "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
	    try {
	        List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
	        System.out.println(list.size());
	        for (int i = 0; i < list.size(); i++) {
	            Map<String, Object> map = list.get(i);
	            Set<String> set = map.keySet();
	            for (Iterator<String> it = set.iterator();it.hasNext();) {
	                String key = it.next();
	                System.out.println(key + ":" + map.get(key));
	            }
	        }
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	/**
	 * <b>function:</b>json字符串转换成Array
	 * @author hoojo
	 * @createDate 2010-11-23 下午06:14:01
	 */
	@Test
	public void readJson2Array() {
	    String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
	            "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
	    try {
	        AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
	        System.out.println(arr.length);
	        for (int i = 0; i < arr.length; i++) {
	            System.out.println(arr[i]);
	        }
	        
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	/**
	 * <b>function:</b>json字符串转换Map集合
	 * @author hoojo
	 * @createDate Nov 27, 2010 3:00:06 PM
	 */
	@SuppressWarnings("unchecked")
	@Test
	public void readJson2Map() {
	    String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
	                "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
	    try {
	        Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
	        System.out.println(maps.size());
	        Set<String> key = maps.keySet();
	        Iterator<String> iter = key.iterator();
	        while (iter.hasNext()) {
	            String field = iter.next();
	            System.out.println(field + ":" + maps.get(field));
	        }
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	/**
	 * <b>function:</b>java对象转换成xml文档
	 * 需要额外的jar包 stax2-api.jar
	 * @author hoojo
	 * @createDate 2010-11-23 下午06:11:21
	 */
	/*
	public void writeObject2Xml() {
	    //stax2-api-3.0.2.jar
	    System.out.println("XmlMapper");
	    XmlMapper xml = new XmlMapper();
	    
	    try {
	        //javaBean转换成xml
	        //xml.writeValue(System.out, bean);
	        StringWriter sw = new StringWriter();
	        xml.writeValue(sw, bean);
	        System.out.println(sw.toString());
	        //List转换成xml
	        List<AccountBean> list = new ArrayList<AccountBean>();
	        list.add(bean);
	        list.add(bean);
	        System.out.println(xml.writeValueAsString(list));
	        
	        //Map转换xml文档
	        Map<String, AccountBean> map = new HashMap<String, AccountBean>();
	        map.put("A", bean);
	        map.put("B", bean);
	        System.out.println(xml.writeValueAsString(map));
	    } catch (JsonGenerationException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
*/

}
